Passed
Pull Request — master (#20)
by Muhammad Dyas
01:34
created

ActionHandler.saveOption   C

Complexity

Conditions 11

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 26
rs 5.4
c 0
b 0
f 0
cc 11

How to fix   Complexity   

Complexity

Complex classes like ActionHandler.saveOption often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import {chat_v1 as chatV1} from 'googleapis/build/src/apis/chat/v1';
2
import BaseHandler from './BaseHandler';
3
import NewPollFormCard from '../cards/NewPollFormCard';
4
import {addOptionToState, getConfigFromInput, getStateFromCard} from '../helpers/state';
5
import {callMessageApi} from '../helpers/api';
6
import {createDialogActionResponse, createStatusActionResponse} from '../helpers/response';
7
import PollCard from '../cards/PollCard';
8
import {ClosableType, MessageDialogConfig, PollFormInputs, PollState, TaskEvent, Voter} from '../helpers/interfaces';
9
import AddOptionFormCard from '../cards/AddOptionFormCard';
10
import {saveVotes} from '../helpers/vote';
11
import {PROHIBITED_ICON_URL} from '../config/default';
12
import ClosePollFormCard from '../cards/ClosePollFormCard';
13
import MessageDialogCard from '../cards/MessageDialogCard';
14
import {createTask} from '../helpers/task';
15
16
/*
17
This list methods are used in the poll chat message
18
 */
19
interface PollAction {
20
  saveOption(): Promise<chatV1.Schema$Message>;
21
22
  getEventPollState(): PollState;
23
}
24
25
export default class ActionHandler extends BaseHandler implements PollAction {
26
  async process(): Promise<chatV1.Schema$Message> {
27
    const action = this.event.common?.invokedFunction;
28
    switch (action) {
29
      case 'start_poll':
30
        return await this.startPoll();
31
      case 'vote':
32
        return this.recordVote();
33
      case 'add_option_form':
34
        return this.addOptionForm();
35
      case 'add_option':
36
        return await this.saveOption();
37
      case 'show_form':
38
        const pollForm = new NewPollFormCard({topic: '', choices: []}, this.getUserTimezone()).create();
39
        return createDialogActionResponse(pollForm);
40
      case 'new_poll_on_change':
41
        return this.newPollOnChange();
42
      case 'close_poll_form':
43
        return this.closePollForm();
44
      case 'close_poll':
45
        return await this.closePoll();
46
      default:
47
        return createStatusActionResponse('Unknown action!', 'UNKNOWN');
48
    }
49
  }
50
51
  /**
52
   * Handle the custom start_poll action.
53
   *
54
   * @returns {object} Response to send back to Chat
55
   */
56
  async startPoll() {
57
    // Get the form values
58
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
59
    const config = getConfigFromInput(formValues);
60
61
    if (!config.topic || config.choices.length === 0) {
62
      // Incomplete form submitted, rerender
63
      const dialog = new NewPollFormCard(config, this.getUserTimezone()).create();
64
      return createDialogActionResponse(dialog);
65
    }
66
    if (config.closedTime) {
67
      // because previously we marked up the time with user timezone offset
68
      config.closedTime -= this.getUserTimezone()?.offset ?? 0;
69
    }
70
    const pollCardMessage = new PollCard({author: this.event.user, ...config}, this.getUserTimezone()).createMessage();
71
    const request = {
72
      parent: this.event.space?.name,
73
      requestBody: pollCardMessage,
74
    };
75
    const apiResponse = await callMessageApi('create', request);
76
    if (apiResponse.data?.name) {
77
      if (config.autoClose && config.closedTime) {
78
        const taskPayload: TaskEvent = {'id': apiResponse.data.name, 'action': 'close_poll', 'type': 'TASK'};
79
        await createTask(JSON.stringify(taskPayload), config.closedTime);
80
        if (config.autoMention) {
81
          const taskPayload: TaskEvent = {'id': apiResponse.data.name, 'action': 'remind_all', 'type': 'TASK'};
82
          await createTask(JSON.stringify(taskPayload), config.closedTime - 420000);
83
        }
84
      }
85
      return createStatusActionResponse('Poll started.', 'OK');
86
    } else {
87
      return createStatusActionResponse('Failed to start poll.', 'UNKNOWN');
88
    }
89
  }
90
91
  /**
92
   * Handle the custom vote action. Updates the state to record
93
   * the user's vote then rerenders the card.
94
   *
95
   * @returns {object} Response to send back to Chat
96
   */
97
  recordVote() {
98
    const parameters = this.event.common?.parameters;
99
    if (!(parameters?.['index'])) {
100
      throw new Error('Index Out of Bounds');
101
    }
102
    const choice = parseInt(parameters['index']);
103
    const userId = this.event.user?.name ?? '';
104
    const userName = this.event.user?.displayName ?? '';
105
    const voter: Voter = {uid: userId, name: userName};
106
    const state = this.getEventPollState();
107
108
    // Add or update the user's selected option
109
    state.votes = saveVotes(choice, voter, state.votes!, state.anon);
110
    const card = new PollCard(state, this.getUserTimezone());
111
    return {
112
      thread: this.event.message?.thread,
113
      actionResponse: {
114
        type: 'UPDATE_MESSAGE',
115
      },
116
      cardsV2: [card.createCardWithId()],
117
    };
118
  }
119
120
  /**
121
   * Opens and starts a dialog that allows users to add details about a contact.
122
   *
123
   * @returns {object} open a dialog.
124
   */
125
  addOptionForm() {
126
    const state = this.getEventPollState();
127
    const dialog = new AddOptionFormCard(state).create();
128
    return createDialogActionResponse(dialog);
129
  };
130
131
  /**
132
   * Handle add new option input to the poll state
133
   * the user's vote then rerenders the card.
134
   *
135
   * @returns {object} Response to send back to Chat
136
   */
137
  async saveOption(): Promise<chatV1.Schema$Message> {
138
    const userName = this.event.user?.displayName ?? '';
139
    const state = this.getEventPollState();
140
    const formValues = this.event.common?.formInputs;
141
    const optionValue = formValues?.['value']?.stringInputs?.value?.[0]?.trim() || '';
142
    addOptionToState(optionValue, state, userName);
143
144
    const cardMessage = new PollCard(state, this.getUserTimezone()).createMessage();
145
146
    const request = {
147
      name: this.event.message!.name,
148
      requestBody: cardMessage,
149
      updateMask: 'cardsV2',
150
    };
151
    const apiResponse = await callMessageApi('update', request);
152
    if (apiResponse.status === 200) {
153
      return createStatusActionResponse('Option is added', 'OK');
154
    } else {
155
      return createStatusActionResponse('Failed to add option.', 'UNKNOWN');
156
    }
157
  }
158
159
  getEventPollState(): PollState {
160
    const stateJson = getStateFromCard(this.event);
161
    if (!stateJson) {
162
      throw new ReferenceError('no valid state in the event');
163
    }
164
    return JSON.parse(stateJson);
165
  }
166
167
  async closePoll(): Promise<chatV1.Schema$Message> {
168
    const state = this.getEventPollState();
169
    state.closedTime = Date.now();
170
    state.closedBy = this.event.user?.displayName ?? '';
171
    const cardMessage = new PollCard(state, this.getUserTimezone()).createMessage();
172
    const request = {
173
      name: this.event.message!.name,
174
      requestBody: cardMessage,
175
      updateMask: 'cardsV2',
176
    };
177
    const apiResponse = await callMessageApi('update', request);
178
    if (apiResponse.status === 200) {
179
      return createStatusActionResponse('Poll is closed', 'OK');
180
    } else {
181
      return createStatusActionResponse('Failed to close poll.', 'UNKNOWN');
182
    }
183
  }
184
185
  closePollForm() {
186
    const state = this.getEventPollState();
187
    if (state.type === ClosableType.CLOSEABLE_BY_ANYONE || state.author!.name === this.event.user?.name) {
188
      return createDialogActionResponse(new ClosePollFormCard().create());
189
    }
190
191
    const dialogConfig: MessageDialogConfig = {
192
      title: 'Sorry, you can not close this poll',
193
      message: `The poll setting restricts the ability to close the poll to only the creator(${state.author!.displayName}).`,
194
      imageUrl: PROHIBITED_ICON_URL,
195
    };
196
    return createDialogActionResponse(new MessageDialogCard(dialogConfig).create());
197
  }
198
199
  newPollOnChange() {
200
    const formValues: PollFormInputs = this.event.common!.formInputs! as PollFormInputs;
201
    const config = getConfigFromInput(formValues);
202
    return createDialogActionResponse(new NewPollFormCard(config, this.getUserTimezone()).create());
203
  }
204
}
205